#include <webx/route.h>

class GetCountList : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(GetCountList)

int GetCountList::process()
{
	auto datmap = app->getTransCountMap();
	JsonElement arr = json.addArray("list");

	param_int(port);
	param_string(host);
	param_string(path);
	param_int(pagenum);
	param_int(pagesize);

	if (host.length() > 0)
	{
		HttpRequest request(getClassName());

		request.setHeadHost(host, port);
		request.setParameter("path", path);
		request.setParameter("pagenum", pagenum);
		request.setParameter("pagesize", pagesize);
	
		SmartBuffer data = request.getResult(host, port);

		if (data.isNull()) return simpleResponse(XG_ERROR);

		out << data.str();

		return XG_OK;
	}

	if (pagenum < 0) pagenum = 0;
	if (pagesize < 1) pagesize = 10;
	if (pagesize > 100) pagesize = 100;

	stdx::tolower(path);

	int daily = 0;
	int realtime = 0;
	vector<string> vec;
	
	for (auto& item : datmap)
	{
		if (path.length() > 0 && item.first.find(path) == string::npos) continue;

		realtime += item.second.realtime;
		daily += item.second.daily;
		vec.push_back(item.first);
	}

	int res = 0;
	int len = vec.size();

	std::sort(vec.begin(), vec.end());

	for (int i = 0; i < len; i++)
	{
		const auto& key = vec[i];
		const auto& item = datmap[key];

		if (res < pagesize && i >= pagenum * pagesize)
		{
			JsonElement data = arr[res++];

			data["realtime"] = item.realtime;
			data["meancost"] = item.meancost;
			data["mincost"] = item.mincost;
			data["maxcost"] = item.maxcost;
			data["daily"] = item.daily;
			data["path"] = key;
		}
	}

	
	json["datetime"] = DateTime::ToString();
	json["realtime"] = realtime;
	json["count"] = vec.size();
	json["daily"] = daily;
	json["code"] = res;
	out << json;

	return XG_OK;
}